/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.nju.zyy.basic.exception;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * 
 * @author yingyzhang
 */
class ExceptionThread2 implements Runnable {

	@Override
	public void run() {
		Thread t = Thread.currentThread();
		System.out.println("   run() by " + t);
		System.out.println("   eh = " + t.getUncaughtExceptionHandler());
		throw new RuntimeException();
	}

}

class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {

	@Override
	public void uncaughtException(Thread t, Throwable e) {
		System.out.println("      caught " + e + " from " + t);
		System.out.println("      over\n");
	}

}

class HandlerThreadFactory implements ThreadFactory {

	@Override
	public Thread newThread(Runnable r) {
		System.out.println("Thread factory is creating new Thread");
		Thread t = new Thread(r);
		System.out.println("created " + t);
		t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
		System.out.println("set eh = " + t.getUncaughtExceptionHandler());
		return t;
	}

}

public class CaptureUncaughtException {
	public static void main(String[] args) {
		ExecutorService exec = Executors
				.newCachedThreadPool(new HandlerThreadFactory());
		exec.execute(new ExceptionThread2());
	}
}
